package com.xiaoyun.rollutil.service.impl;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoyun.rollutil.entity.bo.ApiModelBO;
import com.xiaoyun.rollutil.entity.BarCodeInfo;
import com.xiaoyun.rollutil.mapper.BarCodeInfoMapper;
import com.xiaoyun.rollutil.service.IBarCodeInfoService;
import com.xiaoyun.rollutil.util.RequestUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: XiaoYun461
 * @Date: 2021/12/1 18:27
 *
 */
@Service
@AllArgsConstructor
@Slf4j
public class BarCodeInfoServiceImpl implements IBarCodeInfoService {

    private final BarCodeInfoMapper barCodeInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BarCodeInfo getBarCodeInfo(Long barcode) {
        BarCodeInfo barCodeInfo = barCodeInfoMapper
                .selectOne(new LambdaQueryWrapper<BarCodeInfo>()
                        .eq(BarCodeInfo::getBarcode, barcode));
        if (barCodeInfo != null) {
            return barCodeInfo;
        }
        ApiModelBO apiModelBO = RequestUtil.getBarCodeModel(barcode);
        if (apiModelBO.isSuccess()) {
            barCodeInfo = JSONUtil.toBean((JSONObject) apiModelBO.getData(), BarCodeInfo.class);
        } else {
            log.info("请求错误 条形编码号为:{}, 描述信息为:{}", barcode, apiModelBO.getMsg());
            barCodeInfo.setBarcode(barcode);
        }
        barCodeInfoMapper.insert(barCodeInfo);
        return barCodeInfo;
    }


}
